package www.kingee.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;

public class ServerThread
  implements Runnable
{
  Socket s = null;
  BufferedReader br = null;

  public ServerThread(Socket s) throws IOException { this.s = s;
    this.br = new BufferedReader(new InputStreamReader(s.getInputStream()));
  }

  public void run()
  {
    try
    {
      String content = null;
      while ((content = readFromClient()) != null) {
        System.out.println("从网络读入客户端发来的一条数据：" + content);

        for (Socket s : MyServer.socketList) {
          PrintStream ps = new PrintStream(s.getOutputStream());
          ps.println(content);
          System.out.println("将数据写入链接到服务器的所有客户端，端口：" + s.getPort() + "内容：" + content);
        }
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  private String readFromClient() {
    try {
      return this.br.readLine();
    } catch (IOException e) {
      MyServer.socketList.remove(this.s);
      System.out.println("和一个客户端断开连接");
    }
    return null;
  }
}

